package com.sptpc.demo1.controller;

import com.sptpc.demo1.controller.requests.AddDrinkRequest;
import com.sptpc.demo1.model.Category;
import com.sptpc.demo1.model.Drink;
import com.sptpc.demo1.service.ICategoryService;
import com.sptpc.demo1.service.IDrinkService;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.List;


@Slf4j  //日志
@RestController
@RequestMapping("/drink")
public class DrinkController {

    @Autowired //在合适的地方自动实例化对象；
    private IDrinkService drinkService;
    @Autowired
    private ICategoryService categoryService;
    /**
     * 查询所有
     * get /drink/
     * @return
     */
    @GetMapping("/")
    public List<Drink> getAll(Integer page,Integer limit){
        //分页显示
        PageRequest pageRequest=PageRequest.of(page-1,limit);
        //数据库查询数据
        List<Drink> results=drinkService.getAllDrinks(pageRequest).getContent();
        return results;
    }

    /**
     * 查询指定id
     * get/drink/1  (path表示法)get /drink/
     * @return
     */
    @GetMapping("/{id}")
    public Drink getDrink(@PathVariable Integer id){
        log.info("查询饮品的id: {}",id);
        //  后期从数据库查询
        Drink drink=(Drink.builder().id(1)
                .name("茉莉花茶")
                .price(Money.parse("USD 8.00"))
                .build());
        return drink;
    }

    /**
     * 新增
     * post  /drink/{"name": "奶茶","price": "8.00",“categoryid”:"1"}
     * 1. 直接使用model类接受用户参数
     * 2. 编写一个TO类专门负责传值
     */
    @PostMapping("/")
    public Drink addNewDrink(@RequestBody AddDrinkRequest drink, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            for (ObjectError error : bindingResult.getAllErrors()) {
                log.error(error.toString());
            }
            return null;
        }else {
            log.info("创建新饮品: {}", drink);
            Drink saveDrink = new Drink();
            BeanUtils.copyProperties(drink,saveDrink);
            drinkService.addNewDrink(saveDrink,drink.getCategoryId());
            return saveDrink;
        }
    }

    /**
     * 修改
     * put /drink/{"id": 1, "name": "新奶茶", "price": "10.0"}
     */
    @PutMapping("/")
    public Drink modifyDrink(@RequestBody AddDrinkRequest request){
        log.info("要修改的饮品: {}",request);

        //1. 通过传递的参数拿到分类的id并且通过查询拿到category对象
        Category category=categoryService.getCategoryById(request.getCategoryId());
        Drink saveDrink = new Drink();
        //2. 将request中的值覆盖saveDrink
        BeanUtils.copyProperties(request,saveDrink);
        //3. 设置saveDrink中的category为刚刚查询出来的category。
        saveDrink.setCategory(category);
        //4. 调用更新方法即可
        drinkService.updateDrink(saveDrink);


        
//        // 后期使用数据库update
//        //1. 先通过id查询出对应的数据信息
//        Drink drink=drinkService.getDrinkById(request.getId());
//        //2. 复制前端要修改的属性(将前端传递的值覆盖个drink)
//        BeanUtils.copyProperties(request,drink);
//        //3. 更新数据库
//        drinkService.updateDrink(drink);
        return saveDrink;
    }


    /**
     * 删除
     * delete /drink/1
     */
    @DeleteMapping("/{id}")
    public String deleteDrink(@PathVariable Integer id){
        log.info("要删除的饮品id: {}",id);
        drinkService.delDrink(id);
        //后期使用数据库
        return "删除成功";
    }
    /**
     * 文件上传
     * 前端必须使用html form
     * 前端类型必须设置为 multipart/form-data
     */
    @PostMapping(value = "/upload",consumes ={MediaType.MULTIPART_FORM_DATA_VALUE})
    public String uploadFile(MultipartFile file){
        log.info("参数名 {}", file.getName());
        log.info("上传文件名 {}", file.getOriginalFilename());
        log.info("上传文件大小 {}", file.getSize());

        try {
            String dest="D:\\JavaWeb\\资源上传\\";//文件上传路径
            String destFileName=dest+file.getOriginalFilename();
            File destFile=new File(destFileName);
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("上传失败:{}", e.toString());
            return "上传失败";
        }
        return "上传成功";
    }
    /**
     * 批量上传文档
     * @return
     */
    @PostMapping(value = "/batch",consumes ={MediaType.MULTIPART_FORM_DATA_VALUE})
    public List batchAddNewDrink(MultipartFile file){
        List<Drink> list=new ArrayList<>();
        try {
            InputStreamReader inputStreamReader=new InputStreamReader(file.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line="";
            while ((line=bufferedReader.readLine())!=null){
                String [] args=line.split(",");
                Drink drink= Drink.builder()
                        .id(Integer.parseInt(args[0]))
                        .name(args[1])
                        .price(Money.of(CurrencyUnit.of("CNY"),Double.parseDouble(args[2]))).build();
                list.add(drink);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
